<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="医技分类"> {{ formState?.categoryName || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable
        row-key="id"
        :data-source="dataSource"
        :columns="columns"
        :loading="loading"
        max-fill
        :extra-height="64"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'orderItemName'">
            <EditCell title="对照项目">
              <SelectMedicine :value="{ mc: record.orderItemName }" type="医技对照项目" @select="onSelectMedicine($event, record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'partCode'">
            <EditCell title="部位">
              <a-select v-model:value="record.partCode" mode="multiple" placeholder="请选择" :options="partData" allow-clear />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'dj'">
            <EditCell title="单价">
              <a-input v-model:value="record.dj" v-input:float.3 placeholder="请输入" class="text-right" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <BaseButton confirm-text="确认删除？" type="text" danger size="small" @click="onDelete(record)">删除</BaseButton>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" :disabled="!formState?.categoryCode" type="primary" ghost @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const columns = ref([
  {
    title: '项目名称 ',
    dataIndex: 'orderItemName'
  },
  {
    title: '部位',
    dataIndex: 'partCode'
  },
  {
    title: '单价',
    width: 240,
    dataIndex: 'dj'
  },
  {
    title: '编号',
    width: 240,
    dataIndex: 'orderItemCode'
  },
  {
    title: '操作',
    width: 80,
    dataIndex: 'action'
  }
])

const formState = ref({})
const loading = ref(false)
const dataSource = ref([])
const route = useRoute()
const router = useRouter()
const saveNewRows = async (row) => {
  if (row?.isNew) return
  const newData = dataSource.value
    .filter((i) => i.orderItemName)
    .map((item) => {
      return { ...item, partCode: item.partCode.join(','), ...formState.value }
    })
  const { code, msg } = await post('/ris/dictCategory/doSaveCategoryItem', newData)
  if (code !== 0) return message.error(msg || '操作失败')
  getTableData()
  message.destroy()
  message.success('保存成功')
}

const onSelectMedicine = async (medicine, row) => {
  row.dj = medicine?.dj
  row.orderItemName = medicine?.mc
  row.orderItemCode = medicine?.bh
  await saveNewRows(row)
}
//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true }
  dataSource.value.push(addRow)
}

const onDelete = async (row) => {
  if (row.isNew) {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  } else {
    const { code, msg } = await post('/ris/dictCategory/doRemoveCategoryItem', row)
    if (code !== 0) return message.error(msg || '删除失败')
    message.success(msg)
    getTableData()
  }
}

const getTableData = async () => {
  loading.value = true
  const { data, msg, code } = await post('/ris/dictCategory/getDictCategoryItemList', {
    data: route.query.categoryCode
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  dataSource.value = data.map((item) => ({ ...item, partCode: item.partCode.split(',') }))
}
const partData = ref([])
// 获取部位
const getPositionList = async () => {
  const { code, data } = await post('/operation/opex/getDictPartList', {
    zjm: '',
    pageNum: 1,
    pageSize: 999
  })
  if (code !== 0) return
  partData.value = data.map((item) => {
    return {
      value: item.id,
      label: item.partName
    }
  })
}
// 获取信息
const getInfo = async () => {
  const { code, data, msg } = await post('/ris/dictCategory/getRisCategory', { data: route.query?.categoryCode })
  if (code !== 0) return message.error(msg)
  formState.value = data
}

watchEffect(() => {
  if (route.query.categoryCode) {
    getInfo()
    getPositionList()
    getTableData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-card-head) {
  padding-left: 8px;
}
</style>
